package com.by.basicgateway.nacoslistener;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.by.basicgateway.config.ByServerWebExchangeMatcher;
import com.by.basicgateway.properties.ByGatewayNacosBasicProperties;
import com.by.basicgateway.properties.ByGatewayNacosProperties;
import com.by.basicgateway.utils.ConfigFileConvertUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

import static com.by.toolkit.utils.ExceptionUtil.getStackTrace;

/**
 * @author Tian Wei
 * @version 1.0
 * @date 2023/12/20 1:27 PM
 */
@Data
@Slf4j
@Component
public class NacosGatewayConfigListener {

    @Resource
    private ByGatewayNacosProperties byGatewayNacosProperties;

    @Resource
    private ByServerWebExchangeMatcher byServerWebExchangeMatcher;

    /**
     * 机器启动初始化路由信息
     *
     * @throws NacosException
     */
    @PostConstruct
    public void initGateRouteConfig() throws NacosException {
        ByGatewayNacosBasicProperties propertiesConfig = byGatewayNacosProperties.getConfig();
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, propertiesConfig.getServerAddr());
        if (StringUtils.isNotBlank(propertiesConfig.getNamespace())) {
            properties.put(PropertyKeyConst.NAMESPACE, propertiesConfig.getNamespace());
        }
        ConfigService configService = NacosFactory.createConfigService(properties);
        String configContent = configService.getConfig(propertiesConfig.getDataId(), propertiesConfig.getGroup(), propertiesConfig.getTimeout());
        log.info("[NacosGatewayConfigListener][initGateRouteConfig] configContent:[{}]", configContent);
        refreshFilterPaths(configContent);
        try {
            configService.addListener(propertiesConfig.getDataId(), propertiesConfig.getGroup(), new Listener() {
                @Override
                public void receiveConfigInfo(String configContent) {
                    log.info("[NacosGatewayConfigListener][receiveConfigInfo] configContent:[{}]", configContent);
                    refreshFilterPaths(configContent);
                }

                @Override
                public Executor getExecutor() {
                    //线程
                    return null;
                }
            });
        } catch (NacosException e) {
            log.error("从nacos接收动态路由配置出错!!!,异常信息:{}", getStackTrace(e));
        }

    }

    private void refreshFilterPaths(String configContent) {
        if (StringUtils.isBlank(configContent)) {
            log.info("[NacosGatewayConfigListener][refreshFilterPaths] configContentIsNull");
            return;
        }
        List<String> filterPaths = ConfigFileConvertUtil.converterListByYaml("matcher.filterpaths", configContent, String.class);
        if (CollectionUtil.isEmpty(filterPaths)) {
            log.info("[NacosGatewayConfigListener][refreshFilterPaths] filterPathsIsNull");
            return;
        }
        byServerWebExchangeMatcher.refreshMatch(filterPaths);
    }

}
